import { createHashRouter, RouterProvider } from 'react-router'
// import globalRouter from './globalRouter'
import { useSelector } from 'react-redux'
import { useEffect, useState, lazy } from 'react'
import { initialRouter } from './defaultRouter'

const modules = import.meta.glob('../pages/**/index.jsx')
const components = Object.keys(modules).reduce((prev, cur) => {
  prev[cur.replace('../pages', '').replace('/index.jsx', '')] = modules[cur]
  return prev
}, {})
console.log(components)

// const Users = lazy(() => import('@/pages/users'))

// function globalRoute() {
//   console.log(initialRouter)
//   return createHashRouter(initialRouter)
// }

function Routers() {
  const menu = useSelector(state => state.menu)

  const [routeData, setRouteData] = useState(initialRouter)

  useEffect(() => {
    let newMenu = []
    menu.menuList.forEach(item => {
      let obj = { ...item }
      let El = lazy(components[obj.path])
      obj.element = <El />
      newMenu.push(obj)
    })

    let newRoute = initialRouter.map(item => {
      if(item.path === '/') {
        item.children= item.children.concat(newMenu)
      }
      return item
    })
    setRouteData(newRoute)
  }, [menu.menuList])

  return <RouterProvider router={ createHashRouter(routeData) }></RouterProvider>
}

export default Routers
